{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!--BOOK_INFORMATION-->\n",
    "<img align=\"left\" style=\"padding-right:10px;\" src=\"fig/cover-small.jpg\">\n",
    "*This notebook contains an excerpt from the [Whirlwind Tour of Python](http://www.oreilly.com/programming/free/a-whirlwind-tour-of-python.csp) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/WhirlwindTourOfPython).*\n",
    "\n",
    "*The text and code are released under the [CC0](https://github.com/jakevdp/WhirlwindTourOfPython/blob/master/LICENSE) license; see also the companion project, the [Python Data Science Handbook](https://github.com/jakevdp/PythonDataScienceHandbook).*\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!--NAVIGATION-->\n",
    "< [Basic Python Semantics: Variables and Objects](03-Semantics-Variables.ipynb) | [Contents](Index.ipynb) | [Built-In Types: Simple Values](05-Built-in-Scalar-Types.ipynb) >"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Basic Python Semantics: Operators"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the previous section, we began to look at the semantics of Python variables and objects; here we'll dig into the semantics of the various *operators* included in the language.\n",
    "By the end of this section, you'll have the basic tools to begin comparing and operating on data in Python."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Arithmetic Operations\n",
    "Python implements seven basic binary arithmetic operators, two of which can double as unary operators.\n",
    "They are summarized in the following table:\n",
    "\n",
    "| Operator     | Name           | Description                                            |\n",
    "|--------------|----------------|--------------------------------------------------------|\n",
    "| ``a + b``    | Addition       | Sum of ``a`` and ``b``                                 |\n",
    "| ``a - b``    | Subtraction    | Difference of ``a`` and ``b``                          |\n",
    "| ``a * b``    | Multiplication | Product of ``a`` and ``b``                             |\n",
    "| ``a / b``    | True division  | Quotient of ``a`` and ``b``                            |\n",
    "| ``a // b``   | Floor division | Quotient of ``a`` and ``b``, removing fractional parts |\n",
    "| ``a % b``    | Modulus        | Integer remainder after division of ``a`` by ``b``     |\n",
    "| ``a ** b``   | Exponentiation | ``a`` raised to the power of ``b``                     |\n",
    "| ``-a``       | Negation       | The negative of ``a``                                  |\n",
    "| ``+a``       | Unary plus     | ``a`` unchanged (rarely used)                          |\n",
    "\n",
    "These operators can be used and combined in intuitive ways, using standard parentheses to group operations.\n",
    "For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "42.0"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# addition, subtraction, multiplication\n",
    "(4 + 8) * (6.5 - 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Floor division is true division with fractional parts truncated:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5.5\n"
     ]
    }
   ],
   "source": [
    "# True division\n",
    "print(11 / 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n"
     ]
    }
   ],
   "source": [
    "# Floor division\n",
    "print(11 // 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The floor division operator was added in Python 3; you should be aware if working in Python 2 that the standard division operator (``/``) acts like floor division for integers and like true division for floating-point numbers.\n",
    "\n",
    "Finally, I'll mention an eighth arithmetic operator that was added in Python 3.5: the ``a @ b`` operator, which is meant to indicate the *matrix product* of ``a`` and ``b``, for use in various linear algebra packages."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Bitwise Operations\n",
    "In addition to the standard numerical operations, Python includes operators to perform bitwise logical operations on integers.\n",
    "These are much less commonly used than the standard arithmetic operations, but it's useful to know that they exist.\n",
    "The six bitwise operators are summarized in the following table:\n",
    "\n",
    "| Operator     | Name            | Description                                 |\n",
    "|--------------|-----------------|---------------------------------------------|\n",
    "| ``a & b``    | Bitwise AND     | Bits defined in both ``a`` and ``b``        |\n",
    "| <code>a &#124; b</code>| Bitwise OR      | Bits defined in ``a`` or ``b`` or both      |\n",
    "| ``a ^ b``    | Bitwise XOR     | Bits defined in ``a`` or ``b`` but not both |\n",
    "| ``a << b``   | Bit shift left  | Shift bits of ``a`` left by ``b`` units     |\n",
    "| ``a >> b``   | Bit shift right | Shift bits of ``a`` right by ``b`` units    |\n",
    "| ``~a``       | Bitwise NOT     | Bitwise negation of ``a``                          |\n",
    "\n",
    "These bitwise operators only make sense in terms of the binary representation of numbers, which you can see using the built-in ``bin`` function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'0b1010'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bin(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result is prefixed with ``'0b'``, which indicates a binary representation.\n",
    "The rest of the digits indicate that the number 10 is expressed as the sum $1 \\cdot 2^3 + 0 \\cdot 2^2 + 1 \\cdot 2^1 + 0 \\cdot 2^0$.\n",
    "Similarly, we can write:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'0b100'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bin(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, using bitwise OR, we can find the number which combines the bits of 4 and 10:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "14"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "4 | 10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'0b1110'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bin(4 | 10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These bitwise operators are not as immediately useful as the standard arithmetic operators, but it's helpful to see them at least once to understand what class of operation they perform.\n",
    "In particular, users from other languages are sometimes tempted to use XOR (i.e., ``a ^ b``) when they really mean exponentiation (i.e., ``a ** b``)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Assignment Operations\n",
    "We've seen that variables can be assigned with the \"``=``\" operator, and the values stored for later use. For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "24\n"
     ]
    }
   ],
   "source": [
    "a = 24\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can use these variables in expressions with any of the operators mentioned earlier.\n",
    "For example, to add 2 to ``a`` we write:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "26"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a + 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We might want to update the variable ``a`` with this new value; in this case, we could combine the addition and the assignment and write ``a = a + 2``.\n",
    "Because this type of combined operation and assignment is so common, Python includes built-in update operators for all of the arithmetic operations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "26\n"
     ]
    }
   ],
   "source": [
    "a += 2  # equivalent to a = a + 2\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There is an augmented assignment operator corresponding to each of the binary operators listed earlier; in brief, they are:\n",
    "\n",
    "|||||\n",
    "|-|-|\n",
    "|``a += b``| ``a -= b``|``a *= b``| ``a /= b``|\n",
    "|``a //= b``| ``a %= b``|``a **= b``|``a &= b``|\n",
    "|<code>a &#124;= b</code>| ``a ^= b``|``a <<= b``| ``a >>= b``|\n",
    "\n",
    "Each one is equivalent to the corresponding operation followed by assignment: that is, for any operator \"``■``\", the expression ``a ■= b`` is equivalent to ``a = a ■ b``, with a slight catch.\n",
    "For mutable objects like lists, arrays, or DataFrames, these augmented assignment operations are actually subtly different than their more verbose counterparts: they modify the contents of the original object rather than creating a new object to store the result."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison Operations\n",
    "\n",
    "Another type of operation which can be very useful is comparison of different values.\n",
    "For this, Python implements standard comparison operators, which return Boolean values ``True`` and ``False``.\n",
    "The comparison operations are listed in the following table:\n",
    "\n",
    "| Operation     | Description                       || Operation     | Description                          |\n",
    "|---------------|-----------------------------------||---------------|--------------------------------------|\n",
    "| ``a == b``    | ``a`` equal to ``b``              || ``a != b``    | ``a`` not equal to ``b``             |\n",
    "| ``a < b``     | ``a`` less than ``b``             || ``a > b``     | ``a`` greater than ``b``             |\n",
    "| ``a <= b``    | ``a`` less than or equal to ``b`` || ``a >= b``    | ``a`` greater than or equal to ``b`` |\n",
    "\n",
    "These comparison operators can be combined with the arithmetic and bitwise operators to express a virtually limitless range of tests for the numbers.\n",
    "For example, we can check if a number is odd by checking that the modulus with 2 returns 1:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 25 is odd\n",
    "25 % 2 == 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 66 is odd\n",
    "66 % 2 == 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can string-together multiple comparisons to check more complicated relationships:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# check if a is between 15 and 30\n",
    "a = 25\n",
    "15 < a < 30"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And, just to make your head hurt a bit, take a look at this comparison:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "-1 == ~0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Recall that ``~`` is the bit-flip operator, and evidently when you flip all the bits of zero you end up with -1.\n",
    "If you're curious as to why this is, look up the *two's complement* integer encoding scheme, which is what Python uses to encode signed integers, and think about what happens when you start flipping all the bits of integers encoded this way."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Boolean Operations\n",
    "When working with Boolean values, Python provides operators to combine the values using the standard concepts of \"and\", \"or\", and \"not\".\n",
    "Predictably, these operators are expressed using the words ``and``, ``or``, and ``not``:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = 4\n",
    "(x < 6) and (x > 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(x > 10) or (x % 2 == 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "not (x < 6)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Boolean algebra aficionados might notice that the XOR operator is not included; this can of course be constructed in several ways from a compound statement of the other operators.\n",
    "Otherwise, a clever trick you can use for XOR of Boolean values is the following:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# (x > 1) xor (x < 10)\n",
    "(x > 1) != (x < 10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These sorts of Boolean operations will become extremely useful when we begin discussing *control flow statements* such as conditionals and loops.\n",
    "\n",
    "One sometimes confusing thing about the language is when to use Boolean operators (``and``, ``or``, ``not``), and when to use bitwise operations (``&``, ``|``, ``~``).\n",
    "The answer lies in their names: Boolean operators should be used when you want to compute *Boolean values (i.e., truth or falsehood) of entire statements*.\n",
    "Bitwise operations should be used when you want to *operate on individual bits or components of the objects in question*."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Identity and Membership Operators\n",
    "\n",
    "Like ``and``, ``or``, and ``not``, Python also contains prose-like operators  to check for identity and membership.\n",
    "They are the following:\n",
    "\n",
    "| Operator      | Description                                       |\n",
    "|---------------|---------------------------------------------------|\n",
    "| ``a is b``    | True if ``a`` and ``b`` are identical objects     |\n",
    "| ``a is not b``| True if ``a`` and ``b`` are not identical objects |\n",
    "| ``a in b``    | True if ``a`` is a member of ``b``                |\n",
    "| ``a not in b``| True if ``a`` is not a member of ``b``            |"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Identity Operators: \"``is``\" and \"``is not``\"\n",
    "\n",
    "The identity operators, \"``is``\" and \"``is not``\" check for *object identity*.\n",
    "Object identity is different than equality, as we can see here:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "a = [1, 2, 3]\n",
    "b = [1, 2, 3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a == b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a is b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a is not b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What do identical objects look like? Here is an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = [1, 2, 3]\n",
    "b = a\n",
    "a is b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The difference between the two cases here is that in the first, ``a`` and ``b`` point to *different objects*, while in the second they point to the *same object*.\n",
    "As we saw in the previous section, Python variables are pointers. The \"``is``\" operator checks whether the two variables are pointing to the same container (object), rather than referring to what the container contains.\n",
    "With this in mind, in most cases that a beginner is tempted to use \"``is``\" what they really mean is ``==``."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Membership operators\n",
    "Membership operators check for membership within compound objects.\n",
    "So, for example, we can write:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "1 in [1, 2, 3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "2 not in [1, 2, 3]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These membership operations are an example of what makes Python so easy to use compared to lower-level languages such as C.\n",
    "In C, membership would generally be determined by manually constructing a loop over the list and checking for equality of each value.\n",
    "In Python, you just type what you want to know, in a manner reminiscent of straightforward English prose."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!--NAVIGATION-->\n",
    "< [Basic Python Semantics: Variables and Objects](03-Semantics-Variables.ipynb) | [Contents](Index.ipynb) | [Built-In Types: Simple Values](05-Built-in-Scalar-Types.ipynb) >"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
